package com.ruoyi.web.controller.Region;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import org.apache.poi.poifs.property.Child;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.OliveRegion;
import com.ruoyi.system.service.IOliveRegionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 此为行政区划Controller
 *
 * @author LAN
 * @date 2024-10-29
 */
@RestController
@RequestMapping("/Region/region")
public class OliveRegionController extends BaseController {
    @Autowired
    private IOliveRegionService oliveRegionService;

    /**
     * 查询行政区划列表
     */
    @PreAuthorize("@ss.hasPermi('system:region:list')")
    @GetMapping("/list")
    public TableDataInfo list(OliveRegion oliveRegion) {
        startPage();
        List<OliveRegion> list = oliveRegionService.selectOliveRegionList(oliveRegion);
        return getDataTable(list);
    }

    /**
     * 导出 行政区划列表
     */
    @PreAuthorize("@ss.hasPermi('system:region:export')")
    @Log(title = " 行政区划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OliveRegion oliveRegion) {
        List<OliveRegion> list = oliveRegionService.selectOliveRegionList(oliveRegion);
        ExcelUtil<OliveRegion> util = new ExcelUtil<OliveRegion>(OliveRegion.class);
        util.exportExcel(response, list, " 行政区划数据");
    }

    /**
     * 获取 行政区划详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:region:query')")
    @Anonymous
    @GetMapping(value = "/{regionId}")
    public AjaxResult getInfo(@PathVariable("regionId") Long regionId) {
        return success(oliveRegionService.selectOliveRegionByRegionId(regionId));
    }

    /**
     * 新增 行政区划
     */
    @PreAuthorize("@ss.hasPermi('system:region:add')")
    @Log(title = " 行政区划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OliveRegion oliveRegion) {
        try{
            int result = oliveRegionService.insertOliveRegion(oliveRegion);
            return toAjax(result);
        }catch (DuplicateKeyException e){
            return error("新增区划"+oliveRegion.getRegionName()+"'失败，区划编码已存在'");
        }catch (Exception e){
            return AjaxResult.error("新增区划失败，系统出现错误");
        }
    }

    /**
     * 修改 行政区划
     */
    @PreAuthorize("@ss.hasPermi('system:region:edit')")
    @Log(title = " 行政区划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OliveRegion oliveRegion) {
        return toAjax(oliveRegionService.updateOliveRegion(oliveRegion));
    }

    /**
     * 删除 行政区划
     */
    @PreAuthorize("@ss.hasPermi('system:region:remove')")
    @Log(title = " 行政区划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{regionIds}")
    public AjaxResult remove(@PathVariable Long[] regionIds) {
        return toAjax(oliveRegionService.deleteOliveRegionByRegionIds(regionIds));
    }

    /**
     * 获取 行政区划根据级别
     */
    @PreAuthorize("@ss.hasPermi('system:region:query')")
    @GetMapping(value = "/level/{level}")
    public AjaxResult getInfoBylevel(@PathVariable("level") Integer level) {
        return success(oliveRegionService.selectOliveRegionByLevel(level));
    }

    /**
     * 获取全部行政区划分级信息
     */
    @PreAuthorize("@ss.hasPermi('system:region:query')")
//    @Anonymous
    @GetMapping("/all")
    public AjaxResult getAllInfo() {
        List<OliveRegion> allRegions = oliveRegionService.selectOliveRegionList(new OliveRegion());

        List<Map<String, Object>> jsonTree = allRegions.stream()
                .filter(region -> region.getParentId() == 0) // 筛选出根节点
                .map(region -> {
                    // 递归处理当前区域的子区域
                    Map<String, Object> node = new HashMap<>();
                    node.put("label", region.getRegionName()); // 设置label
                    node.put("value", region.getRegionId()); // 设置value

                    // 递归查找子节点
                    List<Map<String, Object>> children = allRegions.stream()
                            .filter(child -> child.getParentId() != null && child.getParentId().equals(region.getRegionId()))
                            .map(child -> {
                                Map<String, Object> childNode = new HashMap<>();
                                childNode.put("label", child.getRegionName());
                                childNode.put("value", child.getRegionId());

                                // 递归查找孙节点
                                List<Map<String, Object>> grandChildren = allRegions.stream()
                                        .filter(grandChild -> grandChild.getParentId() != null && grandChild.getParentId().equals(child.getRegionId()))
                                        .map(grandChild -> {
                                            Map<String, Object> grandChildNode = new HashMap<>();
                                            grandChildNode.put("label", grandChild.getRegionName());
                                            grandChildNode.put("value", grandChild.getRegionId());
                                            return grandChildNode;
                                        })
                                        .collect(Collectors.toList());

                                childNode.put("children", grandChildren); // 设置子节点
                                return childNode;
                            })
                            .collect(Collectors.toList());

                    node.put("children", children); // 设置子节点
                    return node;
                })
                .collect(Collectors.toList());

        return success(jsonTree);
    }


}
